﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System.ComponentModel;
using System.IO;
using BrainTechLLC.WPF;
using BrainTechLLC;

namespace ImageAppDataModels
{
    public partial class FileImage : BaseNotifyPropertyChangedUI, IHasMD5Hash, INotifyPropertyChanged, IObjectLock, IFileImage
    {
        protected object _md5HashLock = new object();
        protected string _hashValue;

        public string MD5Hash
        {
            get
            {
                if (string.IsNullOrEmpty(_hashValue) && !_deleted)
                {
                    bool setHash = false;

                    lock (_md5HashLock)
                    {
                        if (string.IsNullOrEmpty(_hashValue) && !_deleted)
                        {
                            _hashValue = CalculateMD5Hash();
                            setHash = true;
                        }
                    }

                    if (setHash)
                    {
                        OnPropertyChanged("MD5Hash");
                    }
                }

                return _hashValue;
            }
            set
            {
                if (_hashValue != value)
                {
                    _hashValue = value;
                    OnPropertyChanged("MD5Hash");
                }
            }
        }

        public string MD5HashCached
        {
            get { return _hashValue; }
        }

        protected string CalculateMD5Hash()
        {
            if (_imageBytes == null)
            {
                try
                {
                    byte[] bytes = DataProvider.ReadAllImageBytes(_fileName);
                    return bytes.CalculateMD5Hash();
                }
                catch
                {
                    return string.Empty;
                }
            }
            else
            {
                return _imageBytes.CalculateMD5Hash();
            }
        }
    }
}
